<template>
  <div>
    <el-upload
      :action="url"
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      multiple
      :file-list="fileList"
      :limit="maxCount"
      :on-exceed="handleExceed">
      <el-button size="small" type="primary"><i class="el-icon-upload el-icon--left"></i>点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt/>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'ossUpload',
  props: {
    value: Array,
    maxCount: {
      type: Number,
      default: 5
    }
  },
  data () {
    return {
      url: '',
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: null,
      num: 0,
      successNum: 0
    }
  },
  beforeMount () {
    this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
  },
  methods: {
    emitInput (fileList) {
      let value = []
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url)
      }
      this.$emit('input', value)
    },
    // 上传之前
    beforeUploadHandle (file) {
      if (this.successNum > this.maxCount) {
        this.$message.error(`最多只能上传${this.maxCount}张图片！`)
        return false
      }
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error('只支持jpg、png、gif格式的图片！')
        return false
      }
      this.num++
    },
    // 上传成功
    successHandle (response, file, fileList) {
      this.successNum++
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.fileList.push({
            name: file.name,
            url: response.url
          })
          this.emitInput(this.fileList)
        }
      } else {
        this.$message.error(response.msg)
      }
    },
    // 弹窗关闭时
    closeHandle () {
      this.fileList = []
      this.$emit('refreshDataList')
    },
    handleExceed (files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '张图片',
        type: 'warning',
        duration: 1000
      })
    },
    handleRemove (file, fileList) {
      this.successNum--
      this.num--
      this.emitInput(fileList)
    },
    handlePreview (file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    }
  }
}
</script>

<style scoped>

</style>
